package elitech.vietnam.copyweatherfashion;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;

import elitech.vietnam.copyweatherfashion.config.Const;
import elitech.vietnam.copyweatherfashion.config.Options;
import elitech.vietnam.copyweatherfashion.dialog.ProgressDialogFragment;
import elitech.vietnam.copyweatherfashion.prefs.PrefsDefinition;
import elitech.vietnam.copyweatherfashion.utilities.Utilities;
import elitech.vietnam.copyweatherfashion.wsclient.Service;

public class LoginActivity extends FragmentActivity {

	public static final String	EXTRA_USERID		= "LOGIN_EXTRA_USERID";
	public static int			REQUSET_USERNAME	= 1;

	SharedPreferences			mPrefs;
	Options						mOptions;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		mPrefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
		mOptions = new Gson().fromJson(mPrefs.getString(PrefsDefinition.OPTION, ""), Options.class);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment implements View.OnClickListener {

		LoginActivity	mActivity;
		EditText		mUsername, mPassword;
		Button			mBtnLogin;
		TextView		mTxtRegister, mTxtError;
		CheckBox		mCbAuto;

		public PlaceholderFragment() {
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			mActivity = (LoginActivity) getActivity();
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.fragment_login, container, false);

			mUsername = (EditText) view.findViewById(R.id.edtUsername);
			mPassword = (EditText) view.findViewById(R.id.edtPassword);
			mBtnLogin = (Button) view.findViewById(R.id.btnLogin);
			mCbAuto = (CheckBox) view.findViewById(R.id.chbAutoLogin);
			mTxtRegister = (TextView) view.findViewById(R.id.login_btnRegister);
			mTxtError = (TextView) view.findViewById(R.id.login_text_error);

			mBtnLogin.setOnClickListener(this);
			mTxtRegister.setOnClickListener(this);

			return view;
		}

		@Override
		public void onStart() {
			super.onStart();
			mCbAuto.setChecked(mActivity.mOptions.mAutoLogin);
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnLogin:
				mTxtError.setText("");
				if (mUsername.getText().toString().length() == 0)
					mTxtError.setText(R.string.please_enter_username);
				else if (mPassword.getText().toString().length() == 0)
					mTxtError.setText(R.string.please_enter_password);
				else {
					new LoginTask().execute();
				}
				break;
			case R.id.login_btnRegister:
				Intent intent = new Intent(mActivity, SignupActivity.class);
				startActivityForResult(intent, REQUSET_USERNAME);
				break;
			default:
				break;
			}
		}

		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			if (requestCode == REQUSET_USERNAME && resultCode == LoginActivity.RESULT_OK)
				mUsername.setText(data.getStringExtra(SignupActivity.EXTRAS_SIGNUPUSERNAME));
			super.onActivityResult(requestCode, resultCode, data);
		}

		class LoginTask extends AsyncTask<Integer, Integer, Integer> {
			ProgressDialogFragment	mProgress	= new ProgressDialogFragment.Builder()
														.setTitle(getString(R.string.loading))
														.setMessage(getString(R.string.please_wait)).build();
			int						rs			= -2;

			@Override
			protected void onPreExecute() {
				mProgress.show(getFragmentManager());
			}

			@Override
			protected Integer doInBackground(Integer... params) {
				try {
					int rs1 = 0;
					rs = new Service().logIn(mUsername.getText().toString(),
							Utilities.md5(mPassword.getText().toString()), Const.COUNTRYCODE);
					if (rs > 0) {
						String GCMID = Utilities.getRegistrationId(mActivity.getApplicationContext());
						rs1 = new Service().updateGCM(rs, GCMID);
						if (rs1 <= 0)
							rs = -3;
					}
					return rs;
				} catch (IOException | XmlPullParserException e) {
					e.printStackTrace();
					return -3;
				}
			}

			@Override
			protected void onPostExecute(Integer result) {
				mProgress.dismiss();
				if (result == -1 || result == -2)
					mTxtError.setText(R.string.the_username_or_password_is_incorrect_);
				else if (result == -3)
					mTxtError.setText(R.string.cannot_connect_to_server);
				else {
					mActivity.mOptions.mAutoLogin = mCbAuto.isChecked();
					mActivity.mPrefs.edit().putString(PrefsDefinition.OPTION, new Gson().toJson(mActivity.mOptions))
							.commit();
					Intent intent = new Intent();
					intent.putExtra(EXTRA_USERID, result);
					int mReturnTo = mActivity.getIntent().getIntExtra(MainActivity.EXTRAS_TABRESUME, -1);
					if (mReturnTo > 0)
						intent.putExtra(MainActivity.EXTRAS_TABRESUME, mReturnTo);
					mActivity.setResult(RESULT_OK, intent);
					mActivity.finish();
				}
			}
		}
	}

}
